<template>
  <div class="no-background-container">
    <header-component />
    <div style="height: 60px"></div>
    <el-affix :offset="62">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">
            {{ moduleName }}
          </div>
        </div>
        <div class="header-query">
          <div>
            <el-button type="primary" @click="((isEditMode = false), (showFormDialog = true))">新增{{ moduleName }}</el-button>
          </div>
          <query-form
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams()"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <qs-table
      :finally-columns="finallyColumns"
      :layout="layout"
      :list="list"
      :list-loading="listLoading"
      :query-form="queryForm"
      :total="total"
      @handle-current-change="handleCurrentChange"
      @handle-delete="handleDelete"
      @handle-details="handleDetails"
      @handle-edit="handleEdit"
      @handle-size-change="handleSizeChange"
      @update:query-form="updateQueryForm"
    />
    <!-- 表单弹窗 -->
    <form-dialog
      v-model="showFormDialog"
      :add-params="addParams"
      :form-data="form"
      :module-name="moduleName"
      :title="isEditMode ? '编辑' : '新增'"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, ref } from 'vue'
import Public from '~/src/api/public'
import HeaderComponent from '../components/header.vue'
import type { Department } from './config'
import { addParams, moduleApi, moduleName, searchParams, tableColumns } from './config'

interface ApiResponse<T> {
  code: number
  result: T
}

// 新增 form 变量
const form = ref<Department | object>({})

// 编辑行数据
const handleEdit = (row: Department) => {
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}

// 删除行数据
const handleDelete = (id: Department) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await Public.delApi({ url: moduleApi, id })
        const { code } = response as unknown as ApiResponse<null>
        if (code === 0) {
          ElMessage.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('删除失败:', error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 表格数据
const list = ref<Department[]>([])

// 加载状态
const listLoading = ref<boolean>(true)

// 显示的列
const finallyColumns = computed(() => tableColumns)

// 布局
const layout = 'total, sizes, prev, pager, next, jumper'

// 总条数
const total = ref<number>(0)

// 查询表单
const queryForm = ref({
  page: 1,
  limit: 10,
})

// 控制表单弹窗显示
const showFormDialog = ref(false)

// 是否为编辑模式
const isEditMode = ref(false)

// 获取数据
const fetchData = async () => {
  listLoading.value = true
  try {
    const response = await Public.getDetailApi({ url: moduleApi, params: queryForm.value })
    const { code, result } = response as unknown as ApiResponse<{ rows: Department[]; count: number }>
    console.log(result)
    if (code === 0) {
      list.value = result.rows
      total.value = result.count
    }
  } catch (error) {
    console.error('请求失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

// 当前页改变
const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

// 更新分页信息并重新获取数据
const updatePagination = (params: { page?: number; limit?: number }) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

// 查询数据
const queryData = () => {
  updatePagination({ page: 1 })
}

// 更新查询表单
const updateQueryForm = (value: any) => {
  queryForm.value = value
}

// 表单提交处理
const handleFormSubmit = async (formData: Department) => {
  console.log('表单提交的数据:', formData)
  console.log('isEditMode', isEditMode.value)
  try {
    if (isEditMode.value) {
      const response = await Public.editApi({ url: moduleApi, data: formData })
      const { code } = response as unknown as ApiResponse<null>
      if (code === 0) {
        ElMessage.success('更新成功')
        showFormDialog.value = false
        fetchData()
      }
    } else {
      const response = await Public.addApi({ url: moduleApi, data: formData })
      const { code } = response as unknown as ApiResponse<null>
      if (code === 0) {
        ElMessage.success('添加成功')
        showFormDialog.value = false
        fetchData()
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 查看详情
const handleDetails = (row: Department) => {
  console.log('查看详情:', row)
}

// 初始化
onBeforeMount(() => {
  fetchData()
})

// 激活时重新获取数据
onActivated(() => {
  fetchData()
})
</script>

<style scoped>
.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}
</style>
